//
//  WDPBaseScrollView.m
//  WDPubLib
//
//  Created by wujianrong on 16/4/19.
//  Copyright © 2016年 wanda. All rights reserved.
//

#import "WDPBaseScrollView.h"
#import "UIView+RRZ.h"

typedef void (^EnumArrayBlock)(id obj, NSUInteger idx, BOOL *stop);

@interface WDPBaseScrollView ()
// view 数据源
@property(nonatomic, copy, readonly) NSMutableArray* itemsMutableArray;
@end

@implementation WDPBaseScrollView

#pragma mark- lazy load
/**
 *  lazy load viewSpacing
 *
 *  @return return value description
 */
- (CGFloat)viewSpacing
{
    if (!_viewSpacing) {
        _viewSpacing = 0;
    }
    return _viewSpacing;
}


#pragma mark- init
- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // init
        self.showsHorizontalScrollIndicator = NO;
        self.showsVerticalScrollIndicator = NO;
        self.backgroundColor = [UIColor whiteColor];
        self.pagingEnabled = NO;
        self.directionalLockEnabled = YES;
        self.alwaysBounceVertical = YES;
        self.contentSize = CGSizeMake(0, VIEW_HEIGHT(self));
        self.isWDPScrollEnabled = YES;
        // 默认设置为纵向排列
        self.direction = WDPBaseScrollViewDirectionVertical;
    }
    return self;
}

#pragma mark- insert remove update items

- (NSArray *)itemViewsArray
{
    return [self.itemsMutableArray copy];
}

- (BOOL)hasItemView:(UIView*)item
{
    return [self.itemViewsArray indexOfObject:item] != NSNotFound;
}

- (void)appendOneItemView:(UIView*)itemView
{
    [self appendOneItemView:itemView atIndex:self.itemsMutableArray.count];
}

- (void)appendOneItemView:(UIView *)itemView atIndex:(NSInteger)index
{
    if(itemView == nil)
    {
        return;
    }
    
    if (_itemsMutableArray == nil) {
        _itemsMutableArray = [[NSMutableArray alloc]init];
    }
    if (index > _itemsMutableArray.count) {
        index = _itemsMutableArray.count;
    }
    [_itemsMutableArray insertObject:itemView atIndex:index];
    [self updateAllItemViews];
    [self addSubview:itemView];
}

- (void)appendOneItemView:(UIView *)itemView BehindView:(UIView*)behindView atIndex:(NSInteger)index
{
    if(itemView == nil || behindView == nil)
    {
        return;
    }
    
    if (_itemsMutableArray == nil) {
        _itemsMutableArray = [[NSMutableArray alloc]init];
    }
    
    NSInteger behindViewIndex = [self.itemsMutableArray indexOfObject:behindView];
    
    if (behindViewIndex == NSNotFound) {
        return;
    }
    
    NSInteger itemIndex = behindViewIndex + index;
    
    [_itemsMutableArray insertObject:itemView atIndex:itemIndex];
    [self updateAllItemViews];
    [self addSubview:itemView];
}

- (void)inputWithItemviews:(NSArray*)itemViews
{
    if (itemViews.count) {
        _itemsMutableArray = [NSMutableArray arrayWithArray:itemViews];
    }
    
    [self updateAllItemViews];
    
    __weak typeof(self) weakSelf = self;
    [_itemsMutableArray enumerateObjectsUsingBlock:^(UIView *view, NSUInteger idx, BOOL * _Nonnull stop) {
        [weakSelf addSubview:view];
    }];
}

- (void)removeWithOneItemview:(UIView*)itemView
{
    for (int i=0; i < _itemsMutableArray.count; i++) {
        UIView* view = [_itemsMutableArray objectAtIndex:i];
        if (view == itemView) {
            [itemView removeFromSuperview];
            [_itemsMutableArray removeObject:itemView];
            [self updateAllItemViews];
            break;
        }
    }
    
}

- (void)removeOnItemViewWithIndex:(NSInteger)index
{
    UIView* view = [_itemsMutableArray objectAtIndex:index];
    if (view != nil) {
        [view removeFromSuperview];
        [_itemsMutableArray removeObject:view];
        [self updateAllItemViews];
    }
}

- (void)removeAllItemsView
{
    for (int i=0; i < _itemsMutableArray.count; i++) {
        UIView* view = [_itemsMutableArray objectAtIndex:i];
        if (view) {
            [view removeFromSuperview];
        }
    }
    [_itemsMutableArray removeAllObjects];
    [self updateAllItemViews];
}

- (void)replaceItemAtIndex:(NSInteger)index WithItem:(UIView*)item
{
    if (_itemsMutableArray.count) {
        UIView* view = [_itemsMutableArray objectAtIndex:index];
        [view removeFromSuperview];
        [_itemsMutableArray replaceObjectAtIndex:index withObject:item];
        [self updateAllItemViews];
        [self addSubview:item];
    }
    
}

- (void)updateAllItemViews
{
    __block BOOL isAllItemView = YES;
    
    [self.itemsMutableArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (!([obj isKindOfClass:[WDPBaseItemView class]] || [obj isKindOfClass:[WDPBaseScrollView class]])) {//既不是Base item 也不是BaseScrollView 则不进行上下间距计算 建议使用viewSpacing设置等高间距
            isAllItemView = NO;
            *stop = YES;
        }
    }];
    
    if (isAllItemView) {
        [self updateAllItemViewsFromBaseItemSubView:nil];
    } else {
        [self updateAllItemViewsFromSubView:nil];
    }
}

- (void)updateAllItemViewsFromBaseItemSubView:(WDPBaseItemView*)itemView
{
    EnumArrayBlock block;
    __block CGFloat lastY = 0;
    __block CGFloat lastX = 0;
    long itemCount = _itemsMutableArray.count;
    
    __weak typeof(self) weakSelf = self;
    
    switch (self.direction) {
        case WDPBaseScrollViewDirectionHorizontal:
            // 横向
        {block = ^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx >= itemCount) {
                *stop = YES;
            }
            
            WDPBaseItemView *view = obj;
            [view modifyY:0];
            [view modifyX:lastX+view.wdpMarginLeft];
            [view modifyHeight:VIEW_HEIGHT(weakSelf)];
            CGFloat margin = view.wdpMarginLeft+view.wdpMarginRight;
            // 设置间距
            lastX += VIEW_WIDTH(view) + margin;
        };}
            break;
        case WDPBaseScrollViewDirectionVertical:
            // 默认纵向
        {block = ^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx >= itemCount) {
                *stop = YES;
            }
            
            WDPBaseItemView *view = obj;
            [view modifyX:0];
            [view modifyY:lastY+view.wdpMarginUp];
            [view modifyWidth:VIEW_WIDTH(weakSelf)];
            // 设置间距
            CGFloat margin = view.wdpMarginDown+view.wdpMarginUp;
            lastY += VIEW_HEIGHT(view) + margin;
        };}
            break;
        default:
            
            break;
    }
    
    if (_itemsMutableArray.count) {
        [_itemsMutableArray enumerateObjectsUsingBlock:block];
    }
    [self updateContentSizeWithLast:(self.direction ? lastY:lastX)];
}

- (void)updateAllItemViewsFromSubView:(UIView*)itemView
{
    
    
    EnumArrayBlock block;
    __block CGFloat lastY = 0;
    __block CGFloat lastX = 0;
    long itemCount = _itemsMutableArray.count;
    
    __weak typeof(self) weakSelf = self;
    
    switch (self.direction) {
        case WDPBaseScrollViewDirectionHorizontal:
            // 横向
        {block = ^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx >= itemCount) {
                *stop = YES;
            }
            
            UIView *view = obj;
            [view modifyY:0];
            [view modifyX:lastX];
            [view modifyHeight:VIEW_HEIGHT(weakSelf)];
            CGFloat margin = (idx == itemCount-1)?0:weakSelf.viewSpacing;
            // 设置间距
            lastX += VIEW_WIDTH(view) + margin;
        };}
            break;
        case WDPBaseScrollViewDirectionVertical:
            // 默认纵向
        {block = ^(id obj, NSUInteger idx, BOOL *stop) {
            if (idx >= itemCount) {
                *stop = YES;
            }
            
            UIView *view = obj;
            [view modifyX:0];
            [view modifyY:lastY];
            [view modifyWidth:VIEW_WIDTH(weakSelf)];
            // 设置间距
            CGFloat margin = (idx == itemCount-1)?0:weakSelf.viewSpacing;
            lastY += VIEW_HEIGHT(view) + margin;
        };}
            break;
        default:
            
            break;
    }
    
    if (_itemsMutableArray.count) {
        [_itemsMutableArray enumerateObjectsUsingBlock:block];
    }
    [self updateContentSizeWithLast:(self.direction ? lastY:lastX)];
}

#pragma mark- Others


- (void)updateContentSizeWithLast:(CGFloat)last
{
    if (self.direction) {
        // V
        if (_isWDPScrollEnabled == YES) {
            if (last > VIEW_HEIGHT(self)) {
                self.contentSize = CGSizeMake(0, last);
            }
        }
        else
        {
            self.scrollEnabled = NO;
            [self modifyHeight:last];
        }
    } else {
        // H
        if (_isWDPScrollEnabled == YES) {
            if (last > VIEW_WIDTH(self)) {
                self.contentSize = CGSizeMake(last, 0);
            }
        }
        else
        {
            self.scrollEnabled = NO;
            [self modifyWidth:last];
        }
    }
}

- (void)updateWithDataModel:(id)dataModel callBack:(wdpCallBackBlock)callBack
{
    if (callBack != nil) {
        _callback = callBack;
    }
}

@end
